package com.zkingsoft.zkingbase.base;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.zhy.autolayout.AutoLayoutActivity;
import com.zkingsoft.rxbus.RxBus;
import com.zkingsoft.rxbus.annotation.Tag;
import com.zkingsoft.zkingbase.R;
import com.zkingsoft.zkingbase.manager.AppManager;
import com.zkingsoft.zkingbase.utils.UIHelper;
import com.zkingsoft.zkingbase.view.IBaseView;

import java.io.File;

import butterknife.ButterKnife;

/***
 * 基础activity，所有activity继承这个baseactivity
 * Created by ytf on 2017/03/06
 * 基础activity默认不显示actionbar，(系统主题中设置了)
 */

public abstract class BaseActivity extends AutoLayoutActivity implements IBaseView
{

    public PermissionHelper permissionHelper;
    private PermissionHelper.PermissionCallback bindCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //如果系统sdk大于4.4且允许沉浸式则状态栏沉浸
        transparentStatusbar(isTransparentSupport() && allowTransparentStatus());
        //子类activity需要提供布局文件id
        super.setContentView(getContentView());
        //butternike的view注解绑定
        ButterKnife.bind(this);
        //用于动态申请权限的帮助类
        permissionHelper = PermissionHelper.getInstance();
        //rxbus的注册
        RxBus.get().register(this);
        //所有activity由appmanager进行管理
        AppManager.getInstance().put(this);
    }

    /***
     * 安卓4.4才开始支持透明状态栏
     * @return
     */
    public boolean isTransparentSupport()
    {
        //sdk大于4.4
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    /***
     * 默认不使用沉浸式
     * @return
     */
    public boolean allowTransparentStatus()
    {
        return false;
    }

    /***
     * "沉浸式"状态栏
     */
    public void transparentStatusbar(boolean yn)
    {
        if(yn) getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    /***
     * 调用RxBus发送一条数据
     * @param tag 标签，用于标识事件
     * @param data 数据
     */
    public void rxPost(String tag, Object data)
    {
        RxBus.get().post(tag, data);
    }

    /***
     * 调用RxBus发送一条数据
     * @param data 数据
     */
    public void rxPost(Object data)
    {
        RxBus.get().post(data);
    }

    /***
     * 调整toolbar和状态栏融为一体
     * @param toolbar
     */
    public void adjustToolbar(Toolbar toolbar)
    {
        if(isTransparentSupport())
            toolbar.setPadding(0, UIHelper.getStatusHight()/2,0,0);
    }

    /**
     * 将新的callback绑定为当前callback
     * @param callback
     */
    public void bindCurrentPermissionCallback(PermissionHelper.PermissionCallback callback)
    {
        this.bindCallback = callback;
    }

    /***
     * 权限申请的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            bindCallback.onSuccess();
        } else
        {
            bindCallback.onFailed();
        }
    }

    /***
     * 子类需要在该方法中提供activity的布局
     * @return
     */
    public abstract @LayoutRes int getContentView();

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        //rxbus取消注册
        RxBus.get().unregister(this);
        //activity销毁弹出栈顶
        AppManager.getInstance().pop();
    }

    private Dialog proDialog;
    private TextView tvText;

    /***
     * 显示等待框，默认提示文字是"请稍后..."
     */
    public void showProgress()
    {
        showProgress("请稍后...");
    }

    /***
     * 显示等待框
     * @param proText 提示文字
     */
    public void showProgress(String proText)
    {
        if (proDialog == null)
        {
            proDialog = new Dialog(this, R.style.AlertDialogStyle);
            View view = View.inflate(this, R.layout.progress_bar, null);
            tvText = (TextView) view.findViewById(R.id.show_text);
            view.setVisibility(View.VISIBLE);
            proDialog.setContentView(view);
        }
        if(TextUtils.isEmpty(proText))
        {
            tvText.setVisibility(View.GONE);
        }else
        {
            tvText.setVisibility(View.VISIBLE);
            tvText.setText(proText);
        }
        if (!proDialog.isShowing())
            proDialog.show();
    }

    /***
     * 隐藏等待框
     */
    public void hideProgress()
    {
        if (proDialog != null && (proDialog.isShowing()))
            proDialog.dismiss();
    }

    /***
     * IBaseView的实现，显示等待框
     * @param obj
     */
    @Override
    public void showProgress(Object obj)
    {
        showProgress();
    }

    /***
     * IBaseView的实现，隐藏等待框
     * @param obj
     */
    @Override
    public void hideProgress(Object obj)
    {
        hideProgress();
    }

    /***
     * IBaseView的实现，显示toast
     * @param obj
     */
    @Override
    public void toast(String str, Object obj)
    {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    /***
     * 显示一张图片，占位图和加载错误的图片已经设置了默认
     * @param url   url可以是本地文件绝对路径或者网络地址
     * @param iv    imageview
     */
    public void showImg(String url, ImageView iv, boolean cacheEnable)
    {
        if(url.startsWith("file:"))
        {
            Glide.with(this)
                    .load(new File(url))
                    .error(R.drawable.default_adv)
                    .placeholder(R.drawable.default_adv)
                    .diskCacheStrategy(cacheEnable ? DiskCacheStrategy.SOURCE : DiskCacheStrategy.NONE)
                    .into(iv);
        }else
        {
            Glide.with(this)
                    .load(url)
                    .error(R.drawable.default_adv)
                    .placeholder(R.drawable.default_adv)
                    .diskCacheStrategy(cacheEnable ? DiskCacheStrategy.SOURCE : DiskCacheStrategy.NONE)
                    .into(iv);
        }
    }

}
